#-*- coding:utf-8 -*- 


#####进程池
import multiprocessing
import time
from functools import wraps
import random
import re
import datetime
import copy
import sys
import traceback
import logging


def get_blue_depth(blues):

    depth = []
    for i in range(16):
        depth.append(0)

    for blue in blues:
        if 0 in depth:
            if depth[blue-1] == 0:
                depth[blue-1] = blues.index(blue) + 1

    return depth


def elect_blue():

    lott_his = get_csv_lott_his()

    blues = []

    for lott in lott_his:
        blues.append(lott[6])

    blue_ball_depth = get_blue_depth(blues)


def elect_single_reds(filter_file, elected_blue):###如果传0，则不
    with open(filter_file, 'r') as f:

        ball_dict = {}

        lines = f.readlines()[1:-2]



        for line in lines:

            ball, dist = line.split()
            dist = float(dist)
            if elected_blue == 0:
                ball_dict.setdefault(ball, dist)
            elif ball[6] == elected_blue:
                ball_dict.setdefault(ball, dist)
            else:
                pass


        elected_reds = sorted(ball_dict.items(),key = lambda ball_dict:ball_dict[1], reverse = True)


        print(len(elected_reds))

        print(elected_reds[-10:])

        #print(elected_reds.pop())

    if elected_reds == []:
        return None
    else:
        return elected_reds.pop()


def elect_reds(elected_blue):

    candicates = []

    for i in range(1,29):
        filter_file = '/home/collect/zxx/lot/multiproc/ffile/filter_' + str(i) + '.txt'
        candicate = elect_single_reds(filter_file, elected_blue)
        if candicate != None:
            candicates.append(candicate)
            print(candicate)

    print(sorted(candicates, key = lambda candicates:candicates[1], reverse = True))


       








def get_csv_lott_his():
    lott_his = []
    with open('lottery_his.csv','r') as f:
        lines = f.readlines()

        for line in lines:
            ball_list = []
            balls = line.split(',')[3:]
            lott_his.append(map(int,balls))
    return(lott_his)


def generate_lott_list_csv():
    lott_his = []
    with open('lottery_his.txt','r') as f:
        with open('lottery_his.csv','w+') as csv:
            # lines = f.readlines()[1:].reverse()##直接这么写的话，lines的值为None，a.reverse() 是不可以赋值的
            lines = f.readlines()[1:]
            lines.reverse()
            
            ball_id = 0

            records = []

            for line in lines:

                record = ''

                items = line.strip().split()

                ball_id += 1

                ball_period = items[1]

                ball_date = items[2]

                balls = re.split(',|\\\\',items[3])##re.split可以多分割符分割


                record = str(ball_id) + ',' + ball_period + ',' + ball_date

                for ball in balls:
                    record += ','
                    record += ball

                record += '\n'

                records.append(record)

            csv.writelines(records)


def get_saxon_alpha_dist(a,b):
    dist = 0
    
    ###过滤快乐星期天
    if len(a) > 7:
        a.pop()
    if len(b) > 7:
        b.pop()
    ###过滤快乐星期天
    
    if a.pop() == b.pop():
        dist+=1
    while True:
        try:
            if a[-1] == b[-1]:
                dist += 1
            elif a[-1] > b[-1]:
                a.pop()
            else:
                b.pop()
        except IndexError:
            break

    return dist

def get_saxon_dist(a,b):
    dist = 0
    break_list = [0,0,0,0,0,0,0]
    ###过滤快乐星期天
    if len(a) > 7:
        a.pop()
    if len(b) > 7:
        b.pop()
    ###过滤快乐星期天
    
    if a.pop() == b.pop():
        dist+=1
    while True:
        try:
            if a[-1] == b[-1]:
                dist += 1
            elif a[-1] > b[-1]:
                a.pop()
            else:
                b.pop()
        except IndexError:
            break

    break_list.append(dist)
    return break_list


def get_dist(a,b):
    dist = 0
    
    ###过滤快乐星期天
    if len(a) > 7:
        a.pop()
    if len(b) > 7:
        b.pop()
    ###过滤快乐星期天
    
    if a.pop() == b.pop():
        dist+=1
    for i in a:
            for  j in b:
                    if i==j:
                            dist+=1
    return dist

def fn_timer(function):
    @wraps(function)
    def function_timer(*args, **kwargs):
        t0 = time.time()
        result = function(*args, **kwargs)
        t1 = time.time()
        print ("Total time running %s: %s seconds" %
               (function.func_name, str(t1-t0))
               )
        return result
    return function_timer

@fn_timer
def random_sort(n):
    return sorted([random.random() for i in range(n)])
 

def single_filter(start,lott_his,denominator):
    errFile = 'err_' + str(start) + '.txt'
    try:

        file = './multiproc/ffile/filter_' + str(start) + '.txt'
        file_handle = open(file,'w+')
        start_time = datetime.datetime.now()
        file_handle.write('start from:' + start_time.strftime('%Y-%m-%d %H-%M-%S') + '\n')
        for b in range(start+1,30):
            for c in range(b+1,31):
                for d in range(c+1,32):
                    for e in range(d+1,33):
                        for f in range(e+1,34):
                            for g in range(1,17):
                                candicate = [start,b,c,d,e,f,g]
                                dist = 0
                                continue_flag = 0
                                for his in lott_his:
                                    cp1 = copy.copy(candicate)
                                    cp2 = copy.copy(his)
                                    #this_dist = get_dist(cp1,cp2)
                                    this_dist = get_saxon_dist(cp1,cp2)###使用轩氏距离
                                    if this_dist.pop() > 4:
                                        continue_flag = 1
                                        break
                                    dist += this_dist
                                if continue_flag ==1:
                                    continue
                                avg_dist = float(dist)/denominator

                                line=str(start)+','+str(b)+','+str(c)+','+str(d)+','+str(e)+','+str(f)+','+str(g)+' '+'   '+str(avg_dist)+'\n'

                                file_handle.write(line)
                            #if break_list.pop() == 1:

        end = datetime.datetime.now()
        file_handle.write('stop at:' + end.strftime('%Y-%m-%d %H-%M-%S') + '\n')
        file_handle.write(str((end - start_time).seconds))
        file_handle.close()

    except Exception as e:
        traceback.print_exc(file=open(errFile,'w+'))


#@fn_timer
def main_filter():
    try:
        pool = multiprocessing.Pool(multiprocessing.cpu_count()-1) 

        lott_his = get_csv_lott_his()

        denominator = float(len(lott_his))
        print('denominator:'),
        print(denominator)
        print('type:')
        print(type(denominator))

        for i in range(1,29):
            pool.apply_async(single_filter, (i,lott_his,denominator))###异步进程池

        pool.close()
        pool.join()
    except Exception as e:
        print(e)

 
# if __name__ == '__main__':
        
#     start = datetime.datetime.now()
#     print('start:'+start.strftime('%Y-%m-%d %H-%M-%S-%f'))
#     main_filter()
#     end = datetime.datetime.now()
#     print('stop:'+end.strftime('%Y-%m-%d %H-%M-%S-%f'))

#     print((end - start).seconds)


# elect_single_reds(0)


elect_reds(0)
